<template>
    <view>
        <!-- 导航栏 -->
        <navigationBar :bgType="3" navigationTitle="首页" />

        <view
            class="wrap tabBar-height"
            :style="'padding-top:calc(' + navigationHeight + 'px + 45px);'"
        >
            <image
                class="wrap-bg"
                :src="imageURL + 'common/top_bg.png'"
                mode="widthFix"
            ></image>

            <view
                class="wrap-search flex align-center just-between"
                @click.stop="tieo"
            >
                <view
                    class="address-bg flex align-center"
                    @click.stop="chooseAddress"
                >
                    <view class="city f-26">{{ city }}</view>

                    <image
                        class="arrow"
                        :src="imageURL + 'home/city_arrow.png'"
                    ></image>
                </view>

                <view class="search f-26">搜索内容</view>

                <view class="search-btn f-26">搜索</view>
            </view>

            <view class="wrap-banner">
                <swiper
                    :circular="true"
                    :autoplay="true"
                    :interval="3000"
                    :duration="1000"
                    :indicator-dots="true"
                    indicator-color="rgba(255, 255, 255, 0.3)"
                    indicator-active-color="#FFF"
                >
                    <block v-for="(item, index) in partnerAdverts" :key="index">
                        <swiper-item>
                            <image
                                class="banner-img"
                                :src="'https://same.ascetic.top' + item.media"
                                @click="bannerTab(item.url)"
                            ></image>
                        </swiper-item>
                    </block>
                </swiper>
            </view>

            <view class="wrap-nav flex">
                <block v-for="(item, index) in nav_list" :key="index">
                    <view
                        class="nav-item flex column align-center"
                        @click="toShowPopup(item.link)"
                    >
                        <image
                            class="img"
                            :src="'https://same.ascetic.top' + item.iconImage"
                        ></image>

                        <view class="name f-26">{{ item.text }}</view>
                    </view>
                </block>
            </view>

            <view class="wrap-notice flex align-center">
                <image
                    class="notice-img"
                    :src="imageURL + 'home/notice.png'"
                ></image>

                <view class="notice-list">
                    <swiper
                        :autoplay="true"
                        :interval="3000"
                        :duration="1000"
                        vertical
                        circular
                    >
                        <block v-for="(item, index) in gonggao" :key="index">
                            <swiper-item class="flex align-center">
                                <view
                                    class="title f-26 limit-one-line"
                                    style="line-height: 1.2em"
                                    @click="Jump(item.id)"
                                >
                                    {{ item.title }}
                                </view>
                            </swiper-item>
                        </block>
                    </swiper>
                </view>
            </view>

            <view class="wrap-activity flex just-between">
                <view class="activity-item">
                    <view
                        class="activity-title flex align-center"
                        :style="
                            'background-image: url(' +
                            imageURL +
                            'home/activity_title_bg.png);'
                        "
                    >
                        <view class="title fb-30">拼团活动</view>
                    </view>

                    <scroll-view class="goods-list" scroll-x>
                        <block
                            v-for="(item, index) in pintuanList"
                            :key="index"
                        >
                            <view class="goods-item" @click="toPintuan(item)">
                                <view class="flex column align-center">
                                    <image
                                        class="goods-img"
                                        :src="
                                            'https://same.ascetic.top' +
                                            item.image
                                        "
                                    ></image>

                                    <view class="goods-price">
                                        <text
                                            class="fb-22"
                                            style="margin-right: 6rpx"
                                            >¥</text
                                        >
                                        <text class="fb-30">{{
                                            item.price
                                        }}</text>
                                        <!-- <text class="fb-24">{{ item.price }}</text> -->
                                    </view>
                                </view>
                            </view>
                        </block>
                    </scroll-view>
                </view>

                <view class="activity-item">
                    <view
                        class="activity-title flex align-center"
                        :style="
                            'background-image: url(' +
                            imageURL +
                            'home/activity_title_bg.png);'
                        "
                    >
                        <view class="title fb-30">秒杀活动</view>

                        <view class="activity-time flex align-center">
                            <view class="time f-20">{{ hour }}</view>
                            <view class="colon f-26">:</view>
                            <view class="time f-20">{{ min }}</view>
                            <view class="colon f-26">:</view>
                            <view class="time f-20">{{ second }}</view>
                        </view>
                    </view>

                    <scroll-view class="goods-list" scroll-x>
                        <block
                            v-for="(item, index) in miaoshaList"
                            :key="index"
                        >
                            <view class="goods-item" @click="toFlash()">
                                <view class="flex column align-center">
                                    <image
                                        class="goods-img"
                                        :src="
                                            'https://same.ascetic.top' +
                                            item.image
                                        "
                                    ></image>

                                    <view class="goods-price">
                                        <text
                                            class="fb-22"
                                            style="margin-right: 6rpx"
                                            >¥</text
                                        >
                                        <text class="fb-30">{{
                                            item.price
                                        }}</text>
                                        <!-- <text class="fb-24">{{ item.price }}</text> -->
                                    </view>
                                </view>
                            </view>
                        </block>
                    </scroll-view>
                </view>
            </view>

            <view
                class="wrap-brand"
                :style="
                    'background-image: url(' + imageURL + 'home/brand_bg.png);'
                "
            >
                <view class="brand-title flex just-center fb-32">品牌展示</view>

                <scroll-view class="brand-list flex" scroll-x>
                    <block v-for="(item, index) in activityList" :key="index">
                        <view class="brand-item" @click="goDetail(item.id)">
                            <view class="flex column align-center just-center">
                                <image
                                    class="brand-img"
                                    :src="item.image"
                                ></image>

                                <view class="brand-name">
                                    {{ item.shopname }}
                                </view>
                            </view>
                        </view>
                    </block>
                </scroll-view>
            </view>

            <view class="wrap-recommend">
                <scroll-view class="recommend-category flex" scroll-x>
                    <block v-for="(item, index) in hotListType" :key="index">
                        <view
                            class="category-item"
                            @click.stop="
                                getListBottom(item.name, item.id, index)
                            "
                        >
                            <view class="flex column align-center just-center">
                                <view
                                    class="f-28"
                                    :class="
                                        category_index == index
                                            ? 'title-select'
                                            : 'title-normal'
                                    "
                                >
                                    {{ item.name }}
                                </view>
                                <view
                                    class="subtitle f-20"
                                    :class="
                                        category_index == index
                                            ? 'subtitle-select'
                                            : 'subtitle-normal'
                                    "
                                    >热门推荐</view
                                >
                            </view>
                        </view>
                    </block>
                </scroll-view>

                <view class="recommed-list">
                    <goodsList :goodsList="bottomList" />
                    <u-loadmore :status="status" />
                </view>
            </view>
        </view>
        <u-mask :show="showStart" @click="showStart = false">
            <view class="warp">
                <image
                    class="warp-img"
                    :src="BaseUrl + openAdverts.media"
                    mode="widthFix"
                />
                <button class="cu-btn bg-red" @click="showStart = false">
                    进入首页
                </button>
            </view>
        </u-mask>

        <!-- 工具 -->
        <tool
            :showTop="isShowTop"
            :cartnum="cartnum"
            :shopCart="true"
            :kefu="kefu"
            :costomer="true"
            :showItIndex="showItIndex"
        />
        <!-- tabBar -->
        <tabBar :current="0" />
    </view>
</template>

<script>
import tabBar from "@/components/tabBar/tabBar.vue";
import tool from "@/components/tool/tool.vue";
import amap from "@/utils/amap-wx.130.js";
import { imageURL } from "@/utils/config";
import { BaseUrl } from "@/utils/req.js";
import {
    getShopBanner,
    getRecommendSecondCate,
    getRecommendCate,
    getProductList,
    getActivity,
    getMiaoshaProduct,
} from "@/utils/newLive.js";

export default {
    components: {
        tabBar,
        tool,
    },
    data() {
        return {
            imageURL,
            BaseUrl,
            navigationHeight: uni.getSystemInfoSync()["statusBarHeight"],
            amapPlugins: null, //地图
            city: "",
            nav_list: [],
            hour: "",
            min: "",
            second: "",
            totalTimeCount: 7100,
            countdownInterval: null,
            pintuanList: [],
            isShowTop: false,
            isShopCart: false,
            category_index: 0,
            miaoshaList: [], //秒杀
            cartnum: 0,
            partnerAdverts: [], //首页轮播图
            openAdverts: {}, //首页广告
            gonggao: [], //公告
            kefu: {}, //客服
            activityList: [], //首页品牌活动
            hotListType: [], //热门推荐分类
            bottomList: [], //首页分类列表
            showStart: false,
            shoudong: true, //是否自动定位
            page: 1,
            name: "全部",
            id: 0,
            category_id: 0,
            status: "loadmore",
            showItIndex: 1,
        };
    },
    onShow() {
        this.showItIndex = 1;
        this.isShopCart = !this.isShopCart;
        this.getBannerList(); //首页轮播图
        this.RecommendSecondCate(); //首页分类列表
        this.getPintuan(); //首页拼团
        this.getMiaosha(); //首页秒杀
        this.getActivityList(); //首页品牌活动
        this.getCarts();
        if (!uni.getStorageSync("token")) {
            uni.navigateTo({ url: "/liu/pages/login" });
        }
        if (this.shoudong) {
            this.getAuthorization(); //获取定位
        }
    },
    onLoad() {
        this.amapPlugins = new amap.AMapWX({
            key: "34c09a0a9af59ca04d4c9d9871f685ae",
        });
        this.onCalculationTime();
        this.onCreateTime();
        this.Headline();
        this.RecommendSecondCate(); //首页分类列表
        this.getHotList(); //热门推荐
        this.getListBottom("全部", 0, 0, this.page);
        this.getStart();
    },
    onHide() {
        this.showItIndex = 0;
    },
    /**
     * 页面滑动
     */
    onPageScroll(e) {
        let distanceTop = e.scrollTop;
        if (distanceTop > 200) {
            this.isShowTop = true;
        } else {
            this.isShowTop = false;
        }
    },
    // 触底加载
    onReachBottom() {
        if (this.status == "nomore") return;
        this.status = "loading";
        this.page = this.page + 1;
        this.getListBottom(this.name, this.id, this.category_index, this.page);
    },
    watch: {
        category_index: {
            handler(newName, oldName) {
                this.page = 1;
                this.bottomList = [];
                this.getListBottom(this.name, this.id, this.category_index, this.page);
            },
        },
    },
    /**
     * 方法
     */
    methods: {
        getCarts() {
            this.$request
                .post("api/wanlshop.cart/synchro", { cart: [] })
                .then((res) => {
                    this.cartnum = res.data.length;
                    uni.setStorageSync("cartnum", this.cartnum);
                });
        },
        toFlash() {
            uni.navigateTo({
                url: "/upRelease/flaseSale/flaseSale",
            });
        },
        goDetail(id) {
            uni.navigateTo({
                url: "/dabai/pages/aShop/aShop?id=" + id,
            });
        },
        tieo() {
            uni.navigateTo({
                url: "/upRelease/search/search",
            });
        },
        /**
         * 创建定时
         */
        onCreateTime() {
            this.countdownInterval = setInterval(() => {
                if (this.totalTimeCount == 0) {
                    this.totalTimeCount = 7100;
                }
                this.totalTimeCount--;

                this.onCalculationTime();
            }, 1000);
        },
        // 秒杀请求
        async getMiaosha() {
            const res = await getMiaoshaProduct({
                type: "seckill",
                hour: new Date().getHours(),
            });
            if (res.code == 1) {
                this.miaoshaList = res.data.data;
                this.timeDown(res.data.data[0].endtime);
            }
        },
        timeDown(endTime) {
            //获取当前时间时间戳
            const currentTime = Math.floor(new Date().getTime() / 1000);
            //差值
            const totalTime = endTime - currentTime;
            if (totalTime <= 0) {
                //当前活动结束了
            } else {
                const hour = (Math.floor(totalTime / 3600) % 24)
                    .toString()
                    .padStart(2, 0);
                const min = (Math.floor(totalTime / 60) % 60)
                    .toString()
                    .padStart(2, 0);
                const second = (totalTime % 60).toString().padStart(2, 0);
                this.hour = hour;
                this.min = min;
                this.second = second;
            }
        },
        // 品团请求
        async getPintuan() {
            const res = await getMiaoshaProduct({ type: "groups" });
            if (res.code == 1) {
                this.pintuanList = res.data.data;
            }
        },
        /**
         * 计算时间
         */
        onCalculationTime() {
            this.second = (this.totalTimeCount % 60).toString().padStart(2, 0);
            this.min = (Math.floor(this.totalTimeCount / 60) % 60)
                .toString()
                .padStart(2, 0);
            this.hour = (Math.floor(this.totalTimeCount / 3600) % 24)
                .toString()
                .padStart(2, 0);
        },
        /**
         *
         */
        async getListBottom(name, id, index, page) {
            this.category_index = index;
            this.name = name;
            this.id = id;
            if (name == "全部") {
                const res = await getProductList({ page: page });
                if (res.data.data.length < 15) {
                    this.status = "nomore";
                }
                this.bottomList.push(...res.data.data);
            } else {
                this.RecommendSecond(id, this.page);
            }
        },
        // 底部商品列表
        async RecommendSecond(id, page) {
            const res = await getProductList({
                category_id: id,
                page: page,
            });
            this.bottomList.push(...res.data.data);
        },
        // 种草社区
        toShowPopup(item) {
            if (item.indexOf("http") === 0) {
                uni.navigateTo({
                    url: `/pages/webview?src=${item}`,
                });
            } else {
                uni.navigateTo({
                    url: item,
                });
                uni.switchTab({
                    url: item,
                });
            }
        },
        //首页轮播图
        async getBannerList() {
            const res = await getShopBanner();
            if (res.code == 1) {
                this.partnerAdverts = res.data.data.pageAdverts;
            }
        },
        async getStart() {
            const res = await getShopBanner();
            if (res.code == 1) {
                // 获取开屏广告
                this.openAdverts = res.data.data.openAdverts;
                this.showStart = true;
            }
        },
        //轮播图跳转
        bannerTab(url) {
            if (url.indexOf("http") === 0) {
                uni.navigateTo({
                    url: `/pages/webview?src=${url}`,
                });
            } else {
                if (url == "/upRelease/shangjia/shangjia") {
                    this.$request
                        .post("api/wanlshop.merchant/shop_details", {
                            token: uni.getStorageSync("token"),
                        })
                        .then((res) => {
                            if (res.code == 0 && res.msg == "门店不存在") {
                                uni.navigateTo({
                                    url: "/upRelease/shangjia/shangjia",
                                });
                            } else {
                                uni.showToast({
                                    title: "您已是商家",
                                    icon: "none",
                                    duration: 800,
                                });
                                setTimeout(() => {
                                    uni.navigateTo({
                                        url: "/yCreate/pages/goodsManagement",
                                    });
                                }, 1000);
                            }
                        })
                        .catch((err) => {
                            if (err.code == 0 && err.msg == "门店不存在") {
                                uni.navigateTo({
                                    url: "/upRelease/shangjia/shangjia",
                                });
                            }
                        });
                    return;
                }
                uni.navigateTo({
                    url: url,
                });
            }
        },
        // 跳转种草详情
        Jump(id) {
            uni.navigateTo({
                url: "/dabai/pages/Tickets/Tickets?id=" + id + "&isShow=1",
            });
        },
        // 首页公告
        async Headline() {
            await uni.request({
                url: "https://same.ascetic.top/api/wanlshop.common/notice",
                method: "GET",

                header: {
                    token: uni.getStorageSync("token"),
                },
                success: (res) => {
                    this.gonggao = res.data.data;
                },
            });
        },
        //首页分类列表
        async RecommendSecondCate() {
            const res = await getRecommendSecondCate();
            if (res.code == 1) {
                this.nav_list = res.data.modulesData.homeModules.item[1].data; //分类
                this.nav_list.forEach((item) => {
                    //（改）
                    if (item.text == "平台直播") {
                        item.link = "/pages/shop/live/live.nvue";
                    }
                });
                this.kefu = res.data.kefu;
                let i = this.kefu.kefu_tips.split("客服电话");
                this.kefu.kefu_tips = i[0];
                this.kefu.mobile = i[1];
                uni.setStorageSync("domain", res.data.appConfig.domain);
            }
        },
        // 首页品牌活动
        async getActivityList() {
            const res = await getActivity({});
            if (res.code == 1) {
                this.activityList = res.data;
            }
        },
        // 获取底部热门推荐
        async getHotList() {
            const res = await getRecommendCate({});
            if (res.code == 1) {
                res.data.unshift({ name: "全部", type: 0, id: 0 });
                this.hotListType = res.data;
            }
        },
        toPintuan(item) {
            uni.navigateTo({
                url: "/pages/apps/groups/goods?id=" + item.id,
            });
        },
        // 默认获取定位
        getAuthorization() {
            uni.authorize({
                scope: "scope.userLocation",
                success: (result) => {
                    if (result.errMsg == "authorize:ok") {
                        this.amapPlugins.getRegeo({
                            success: async (res) => {
                                this.city =
                                    res[0].regeocodeData.addressComponent.city; //市
                            },
                            fail: (error) => {
                                console.log(error);
                            },
                        });
                    } else {
                        console.log("拒绝授权");
                    }
                },
                fail: (error) => {},
            });
        },
        //手动选择定位
        chooseAddress() {
            this.shoudong = false;
            uni.authorize({
                scope: "scope.userLocation",
                success: (result) => {
                    if (result.errMsg == "authorize:ok") {
                        uni.getLocation({
                            success: (position) => {
                                uni.chooseLocation({
                                    success: (data) => {
                                        var reg =
                                            /.+?(省|市|自治区|自治州|县|区)/g; // 省市区的正则
                                        let matches = data.address.match(reg);
                                        console.log(matches, "手动选择定位");

                                        // 直接查找包含"市"的匹配项
                                        let city = matches.find((item) =>
                                            item.includes("市")
                                        );
                                        if (city) {
                                            this.city = city;
                                        } else {
                                            console.log("未找到市信息");
                                        }
                                        // this.shoudong = true;
                                    },
                                    fail(err) {
                                        console.log(err);
                                    },
                                });
                            },
                            fail(err) {
                                console.log(err);
                            },
                        });
                    } else {
                        console.log("拒绝授权");
                    }
                },
                fail: (error) => {},
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.wrap {
    width: 100%;
    min-height: 100vh;
    overflow: hidden;
    position: relative;
    padding: 0 25rpx;
    box-sizing: border-box;

    .wrap-bg {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        z-index: -1;
    }

    .wrap-search {
        margin-top: 10rpx;
        width: 700rpx;
        height: 62rpx;
        background-color: white;
        border-radius: 50rpx;
        overflow: hidden;

        .address-bg {
            margin-left: 17rpx;
            overflow: hidden;
            padding: 0 20rpx;
            height: 26rpx;
            border-right: 2rpx solid $line-color;

            .city {
                color: $text-color;
            }

            .arrow {
                margin-top: 5rpx;
                margin-left: 10rpx;
                width: 16rpx;
                height: 16rpx;
            }
        }

        .search {
            margin-left: 20rpx;
            flex: 1;
            color: $place-color;
        }

        .search-btn {
            width: 115rpx;
            height: 54rpx;
            line-height: 54rpx;
            text-align: center;
            color: white;
            background: linear-gradient(90deg, #00a67a, #057748);
            margin-right: 5rpx;
            border-radius: 27rpx;
            overflow: hidden;
        }
    }

    .wrap-banner {
        margin-top: 20rpx;
        width: 700rpx;
        height: 330rpx;
        border-radius: 20rpx;
        overflow: hidden;

        .banner-img {
            width: 700rpx;
            height: 330rpx;
        }
    }

    .wrap-nav {
        margin-top: 15rpx;
        width: 700rpx;
        padding: 25rpx 15rpx 15rpx;
        background-color: white;
        border-radius: 16rpx;
        overflow: hidden;
        flex-wrap: wrap;
        box-sizing: border-box;

        .nav-item {
            width: 25%;
            overflow: hidden;
            margin-bottom: 20rpx;

            .img {
                width: 102rpx;
                height: 102rpx;
            }

            .name {
                margin-top: 15rpx;
                color: $title-color;
            }
        }
    }

    .wrap-notice {
        margin-top: 15rpx;
        width: 700rpx;
        height: 68rpx;
        background-color: white;
        border-radius: 16rpx;
        overflow: hidden;
        padding: 0 17rpx;
        box-sizing: border-box;

        .notice-img {
            width: 42rpx;
            height: 42rpx;
        }

        .notice-list {
            margin-left: 20rpx;
            flex: 1;
            height: 40rpx;

            .title {
                color: $text-color;
            }
        }
    }

    .wrap-activity {
        margin-top: 15rpx;
        width: 700rpx;
        overflow: hidden;

        .activity-item {
            width: 344rpx;
            border-radius: 16rpx;
            overflow: hidden;
            background-color: white;

            .activity-title {
                width: 344rpx;
                height: 69rpx;
                background-size: cover;
                background-repeat: no-repeat;
                background-position: center;
                padding: 10rpx 25rpx 0rpx 25rpx;
                box-sizing: border-box;

                .title {
                    color: $text-color;
                }

                .activity-time {
                    margin-left: 15rpx;
                    flex: 1;
                    overflow: hidden;

                    > view {
                        height: 32rpx;
                        line-height: 32rpx;
                        text-align: center;
                        overflow: hidden;
                    }

                    .time {
                        width: 32rpx;
                        border-radius: 50%;
                        background: linear-gradient(-90deg, #f98a2d, #eb5c20);
                        color: white;
                    }

                    .colon {
                        width: 18rpx;
                        color: $colon-color;
                    }
                }
            }

            .goods-list {
                margin-top: 10rpx;
                width: 100%;
                padding: 0rpx 30rpx 30rpx;
                box-sizing: border-box;
                height: 200rpx;
                white-space: nowrap;

                .goods-item {
                    display: inline-block;
                    margin-right: 35rpx;

                    &:last-child {
                        margin-right: 0rpx;
                    }

                    .goods-img {
                        width: 120rpx;
                        height: 120rpx;
                    }

                    .goods-price {
                        margin-top: 10rpx;
                        color: $price-color;
                    }
                }
            }
        }
    }

    .wrap-brand {
        margin-top: 30rpx;
        width: 700rpx;
        height: 350rpx;
        background-size: cover;
        background-repeat: no-repeat;
        background-position: center;
        overflow: hidden;

        .brand-title {
            width: 100%;
            margin-top: 12rpx;
            color: white;
        }

        .brand-list {
            margin-top: 55rpx;
            width: 100%;
            height: 208rpx;
            box-sizing: border-box;
            padding: 0 25rpx;
            overflow: hidden;
            white-space: nowrap;

            .brand-item {
                width: 186rpx;
                height: 208rpx;
                border-radius: 20rpx;
                overflow: hidden;
                background-color: white;
                margin-right: 20rpx;
                display: inline-block;

                > view {
                    width: 100%;
                    height: 100%;
                }

                &:last-child {
                    margin-right: 0rpx;
                }

                .brand-img {
                    width: 130rpx;
                    height: 130rpx;
                }

                .brand-name {
                    margin-top: 12rpx;
                    color: $text-color;
                }
            }
        }
    }

    .wrap-recommend {
        margin-top: 20rpx;
        width: 100%;
        overflow: hidden;

        .recommend-category {
            width: 100%;
            overflow: hidden;
            white-space: nowrap;

            .category-item {
                display: inline-block;
                width: 180rpx;
                padding: 20rpx 0;

                > view {
                    width: 100%;
                    height: 100%;
                    border-right: 4rpx solid $line-color;
                }

                .title-normal {
                    color: $text-color;
                }

                .title-select {
                    color: $theme-color;
                }

                .subtitle {
                    margin-top: 12rpx;
                    height: 30rpx;
                    line-height: 30rpx;
                    text-align: center;
                    padding: 0 13rpx;
                    overflow: hidden;
                    border-radius: 15rpx;
                    overflow: hidden;
                }

                .subtitle-normal {
                    color: $subtitle-color;
                }

                .subtitle-select {
                    color: white;
                    background: linear-gradient(90deg, #00a67a, #057748);
                }
            }
        }

        .recommed-list {
            margin-top: 20rpx;
            width: 100%;
            overflow: hidden;
        }
    }
}
.warp {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    box-sizing: border-box;
    &-img {
        padding: 20rpx;
    }
    button {
        margin-top: 30rpx;
        width: 60vw;
        height: 80rpx;
        line-height: 80rpx;
        border-radius: 40rpx;
        font-size: 28rpx;
        color: white;
    }
}
</style>
